package com.cyl.XmlDemo.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cyl.XmlDemo.dao.FriendDao;
import com.cyl.XmlDemo.dao.UserDao;
import com.cyl.XmlDemo.entity.Friend;
import com.cyl.XmlDemo.entity.User;

@Service
public class FriendsServiceImpl implements FriendsService {
	
	private final Logger log = LoggerFactory.getLogger(FriendsServiceImpl.class);
	
	@Autowired
	private RoomService roomService;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private FriendDao friendDao;

	@Override
	public List<Friend> getFriendsByUid(int uid) {
		return friendDao.selectFriendByUid(uid);
	}

	@Override
	public String addFriend(Friend friend) {
		//检查欲添加的联系人是否存在
		User user = userDao.findUniqueByAccount(friend.getUsername());
		if(user != null){
			//如果存在则生成通信码，添加联系人
			friend.setUserid(user.getId());
			String cantactcode = duplicateContactCodeById(friend.getUserid(),friend.getRecord());
			if(cantactcode == null){
				cantactcode = roomService.createNum(11);
			}
			friend.setContactcode(cantactcode);
			try{
				
			}catch(Exception e){
				log.debug("添加联系人",e);
				return "error-operation";
			}
			friendDao.addFriend(friend);
			return "success";
		}else{
			return "error-user-null";
		}
	}

	@Override
	public boolean delFriend(Friend friend) {
		friendDao.delFriend(friend);
		return true;
	}

	@Override
	public String duplicateContactCodeById(int record,int userid) {
		Friend friend = new Friend();
		friend.setRecord(record);
		friend.setUserid(userid);
		return friendDao.duplicateContactCodeById(friend);
	}

}
